package com.taiyi.renaissancemall.ui.mine.order.evaluation;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.PersistableBundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.bumptech.glide.Glide;
import com.taiyi.renaissancemall.R;
import com.taiyi.renaissancemall.Utils.ToastUtils;
import com.taiyi.renaissancemall.base.BaseActivity;
import com.taiyi.renaissancemall.base.MyApp;
import com.taiyi.renaissancemall.bean.FindExpressBean;
import com.taiyi.renaissancemall.bean.OrderDetailBean;
import com.taiyi.renaissancemall.bean.RefundResultBean;
import com.taiyi.renaissancemall.bean.VerifiedBean;
import com.taiyi.renaissancemall.ui.mine.order.sale.refund.ApplyRefundDocsAdapter;
import com.taiyi.renaissancemall.ui.mine.order.sale.refund.ApplyRefundPresent;
import com.taiyi.renaissancemall.ui.mine.order.sale.refund.ApplyRefundView;
import com.taiyi.renaissancemall.ui.mine.verified.BaseBottomView;
import com.taiyi.renaissancemall.view.RatingBarView;

import org.devio.takephoto.app.TakePhoto;
import org.devio.takephoto.app.TakePhotoActivity;
import org.devio.takephoto.app.TakePhotoImpl;
import org.devio.takephoto.model.InvokeParam;
import org.devio.takephoto.model.TContextWrap;
import org.devio.takephoto.model.TResult;
import org.devio.takephoto.permission.InvokeListener;
import org.devio.takephoto.permission.PermissionManager;
import org.devio.takephoto.permission.TakePhotoInvocationHandler;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

import butterknife.OnClick;


//评价
public class EvaluationActivity extends BaseActivity<EvaluationView, EvaluationPresent> implements EvaluationView, TakePhoto.TakeResultListener, InvokeListener {

    @BindView(R.id.top)
    ConstraintLayout top;
    @BindView(R.id.backIv)
    ImageView backIv;
    @BindView(R.id.titleTv)
    TextView titleTv;
    @BindView(R.id.rightIv)
    ImageView rightIv;
    @BindView(R.id.iv_shop_icon)
    ImageView ivShopIcon;
    @BindView(R.id.tv_shop_name)
    TextView tvShopName;
    @BindView(R.id.tv_shop_size)
    TextView tvShopSize;
    @BindView(R.id.tv_shop_num)
    TextView tvShopNum;
    @BindView(R.id.tv_shop_price)
    TextView tvShopPrice;
    @BindView(R.id.tv_refund_goods_status)
    TextView tvRefundGoodsStatus;
    @BindView(R.id.rb_choose)
    RatingBarView rbChoose;
    @BindView(R.id.edt_evaluation)
    EditText edtEvaluation;
    @BindView(R.id.rcl_upload_doc)
    RecyclerView rclUploadDoc;
    @BindView(R.id.ll_upload_doc)
    LinearLayout llUploadDoc;
    @BindView(R.id.btn_commit)
    Button btnCommit;

    private String oId;

    private String get_photo = "";
    private TakePhoto takePhoto;
    private InvokeParam invokeParam;
    private static final String TAG = TakePhotoActivity.class.getName();
    private String mImagePath = Environment.getExternalStorageDirectory() + "";
    private String mImageName = "/wanlimall/" + System.currentTimeMillis() + ".jpg";
    private String path = "";
    private Uri imageUri = null;
    private TextView headChangePopupBlack;
    private Button takePhotoBtn;
    private Button pickPhotoBtn;
    private Button cancelBtn;
    private BaseBottomView bottomView;
    private boolean isXiangCe = false;
    private String iconPath = "";
    private ApplyRefundDocsAdapter applyRefundDocsAdapter;

    private List<String> str_imgList = new ArrayList<>();//图片集合
    private StringBuffer doc_buffer = new StringBuffer();
    private String eImg = "";
    private String eBody = "";
    private String eType = "";
    private String getOSSUrl = "";
    private int starsImgHeight;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_evaluation;
    }

    @Override
    public EvaluationPresent initPresenter() {
        return new EvaluationPresent();
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        getTakePhoto().onCreate(savedInstanceState);
        oId = getIntent().getStringExtra("oId");
        titleTv.setText(getString(R.string.evaluation));
        bottomView = new BaseBottomView(this, R.layout.act_photo);
        headChangePopupBlack = ((TextView) bottomView.findViewById(R.id.headChangePopupBlackId));
        takePhotoBtn = (Button) bottomView.findViewById(R.id.takePhotoBtnId);
        pickPhotoBtn = (Button) bottomView.findViewById(R.id.pickPhtotBtnId);
        cancelBtn = (Button) bottomView.findViewById(R.id.cancel_btnId);
        bottomView.setCancelable(true);

        rbChoose.setOnRatingListener(new RatingBarView.OnRatingListener() {
            @Override
            public void onRating(Object bindObject, int RatingScore) {
//                ToastUtils.showShortToast(String.valueOf(RatingScore));
                if (RatingScore < 3) {
                    eType = "3";
                } else if (RatingScore > 3) {
                    eType = "1";
                } else {
                    eType = "2";
                }
            }
        });
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
        mImmersionBar.titleBar(top).init();
    }

    @Override
    protected void initData() {

        showProgress();
        presenter.getOrderDetail(oId);

//        rbChoose.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
//            @Override
//            public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
//                if (rating < 3) {
//                    eType = "3";
//                } else if (rating > 3) {
//                    eType = "1";
//                } else {
//                    eType = "2";
//                }
//            }
//        });

        //关闭选择界面
        cancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomView.dismiss();
            }
        });

        //选择相册
        pickPhotoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isXiangCe = true;
                imageUri = getImageCropUri();
                //从相册中选取不裁剪
                takePhoto.onPickFromGallery();
            }
        });

        //选择拍照
        takePhotoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isXiangCe = false;
                imageUri = getImageCropUri();
                //仅仅拍照不裁剪
                takePhoto.onPickFromCapture(imageUri);
            }
        });

        headChangePopupBlack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomView.dismiss();
            }
        });
    }

    @Override
    public void initEvent() {

    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState, @NonNull PersistableBundle outPersistentState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState, outPersistentState);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
    }

    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }

    @Override
    public void takeSuccess(TResult result) {
        if (bottomView.isShowing()) {
            bottomView.dismiss();
        }
        iconPath = result.getImage().getOriginalPath();
        if (isXiangCe) {
            uploadFileToOSS(iconPath);
        } else {
            uploadFileToOSS(path);
        }
        Log.i(TAG, "takeSuccess：" + result.getImage().getCompressPath() + "==" + result.getImage().getOriginalPath());

    }

    /**
     * 图片列表
     *
     * @param str_imgList
     */
    private void setAdapter(List<String> str_imgList) {
        rclUploadDoc.setVisibility(View.VISIBLE);
        applyRefundDocsAdapter = new ApplyRefundDocsAdapter(R.layout.layout_uplode_doc, str_imgList);
        rclUploadDoc.setLayoutManager(new GridLayoutManager(EvaluationActivity.this, 3));
        rclUploadDoc.setAdapter(applyRefundDocsAdapter);
        applyRefundDocsAdapter.notifyDataSetChanged();
    }

    @Override
    public void takeFail(TResult result, String msg) {
        Log.i(TAG, "takeFail:" + msg);
    }

    @Override
    public void takeCancel() {
        Log.i(TAG, getResources().getString(R.string.msg_operation_canceled));
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    //获得照片的输出保存Uri
    private Uri getImageCropUri() {
        File file = new File(mImagePath, mImageName);
        path = mImagePath + mImageName;
        if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
        return Uri.fromFile(file);
    }

    @OnClick({R.id.backIv, R.id.ll_upload_doc, R.id.btn_commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.backIv:
                finish();
                break;
            case R.id.ll_upload_doc:
                bottomView.show();
                break;
            case R.id.btn_commit:
                eImg = doc_buffer.toString().trim();
                if (doc_buffer.toString().trim().endsWith(",")) {
                    eImg = doc_buffer.toString().trim().substring(0, doc_buffer.toString().trim().length() - 1);
                }
                Log.d("评价", eImg);
                eBody = edtEvaluation.getText().toString().trim();
                if (TextUtils.isEmpty(eType)) {
                    ToastUtils.showLongToast("请选择星级");
                    return;
                }
                if (TextUtils.isEmpty(eBody)) {
                    ToastUtils.showLongToast("请填写评价内容");
                    return;
                }
                if (TextUtils.isEmpty(eImg)) {
                    ToastUtils.showLongToast("请上传图片");
                    return;
                }
                showProgress();
                //1好评2中评3差评
                presenter.toCommitEvaluation(oId, eType, eImg, eBody);
                break;
        }
    }

    @Override
    public void getOrderDetailSuccess(OrderDetailBean orderDetailBean) {
        hideProgress();
        if (!"".equals(orderDetailBean.getOrder().getImgurl())
                && orderDetailBean.getOrder().getImgurl() != null) {
            Glide.with(EvaluationActivity.this).load(orderDetailBean.getOrder().getSmallimgurl()).into(ivShopIcon);
        }
        String sName = "";
        if (orderDetailBean.getOrder().getName().contains("\r\n")) {
            sName = orderDetailBean.getOrder().getName().replace("\r\n", "");
        } else {
            sName = orderDetailBean.getOrder().getName();
        }
        tvShopName.setText(sName);
        tvShopSize.setText(orderDetailBean.getOrder().getTypename());
        String sNum = "X" + orderDetailBean.getOrder().getNumber();
        tvShopNum.setText(sNum);
        tvShopPrice.setText(String.valueOf(orderDetailBean.getOrder().getSumprice()));
    }

    @Override
    public void getOrderDetailFailure(String msg) {
        hideProgress();
        ToastUtils.showLongToast(msg);
    }

    @Override
    public void toEvaluationSuccess(String msg_cn) {
        hideProgress();
//        ToastUtils.showLongToast(msg_cn);
        finish();
    }

    @Override
    public void toEvaluationFailure(String msg) {
        hideProgress();
        ToastUtils.showLongToast(msg);
    }

    private void uploadFileToOSS(String iconPath) {
        String[] strings = iconPath.split("/");
        String name = strings[strings.length - 1];
        OSSClient ossClient = MyApp.getOssClient();
        // 构造上传请求。
        PutObjectRequest put = new PutObjectRequest("wlshop-app", name, iconPath);

        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
            }
        });

        OSSAsyncTask task = ossClient.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.d("PutObject", "UploadSuccess");
                        Log.d("ETag", result.getETag());
                        Log.d("RequestId", result.getRequestId());
                        getOSSUrl = ossClient.presignPublicObjectURL("wlshop-app", name);
                        Log.d("servercallback", "1--" + getOSSUrl);
                        get_photo = getOSSUrl;
                        //将图片传给列表
                        str_imgList.add(get_photo);
                        if (str_imgList.size() == 6) {
                            llUploadDoc.setVisibility(View.GONE);
                        }
                        doc_buffer.append(get_photo);
                        doc_buffer.append(",");
                        setAdapter(str_imgList);
                    }
                });
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                ToastUtils.showLongToast("图片上传异常");
                // 请求异常。
                if (clientExcepion != null) {
                    // 本地异常，如网络异常等。
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常。
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                }
            }
        });
        // task.cancel(); // 可以取消任务。
        // task.waitUntilFinished(); // 等待任务完成。
    }

}
